<?php


namespace app\service\utils;


use app\common\Consts;
use app\common\exception\ApiException;
use app\common\SmsCode;
use app\model\coach\UserCoachModel;
use app\model\partner\UserPartnerModel;
use app\model\user\UserModel;
use app\model\user\UserSmsModel;
use app\service\BaseService;

use Exception;
use think\facade\Cache;

class SmsService extends BaseService
{

    public static function getInstance()
    {
        return new UserSmsModel();
    }

    public function __construct()
    {
    }

    /**
     * 发送短信
     * @param $mobile
     * @param $type
     * @return bool
     * @throws APiException
     */
    public static function sendSms($mobile, $type)
    {
        try {
            if (!isPhoneNumber($mobile)) {
                throw new APiException('手机号格式错误');
            }
            $key = 'sms:mobile:' . $mobile . ':type:' . $type;
            $code = rand(111111, 999999);
            if (Cache::get($key)) {
                throw new APiException('发送频繁，请稍后再试');
            }
            Cache::set($key, $code, 60);
//            if ($type == SmsCode::ADMIN_LOGIN) {
//                // 后台管理端短信登录
//                $info = UserModel::where('mobile', $mobile)->find();
//                if (!$info) {
//                    throw new APiException('用户不存在');
//                }
//                if (!$info['status']) {
//                    throw new APiException('用户禁止登录');
//                }
//                if (!in_array($info['role_id'], [Consts::ADMIN_ROLE_ID])) {
//                    throw new APiException('非法请求');
//                }
//            } elseif ($type == SmsCode::APP_LOGIN) {
//                // ApP登陆
//                $info = UserPartnerModel::where('mobile', $mobile)->find();
//                if (!$info) {
//                    throw new APiException('账号未注册');
//                }
//            } elseif ($type == SmsCode::APP_REGISTER) {
//                // APP注册
//                $info = UserModel::where('mobile', $mobile)->find();
//                if ($info) {
//                    throw new APiException('手机号已被占用');
//                }
//            } elseif ($type == SmsCode::APP_FORGOT_PWD) {
//                // APP 找回密码
//                $info = UserModel::where('mobile', $mobile)->find();
//                if (!$info) {
//                    throw new APiException('账号不存在');
//                }
//            } elseif ($type == SmsCode::APP_CHANG_MOBILE) {
//                // APP换绑手机号
//                $info = UserModel::where('mobile', $mobile)->find();
//                if ($info) {
//                    throw new APiException('手机号已被占用');
//                }
//            } elseif ($type == SmsCode::WRITE_OFF) {
//                // APP 注销
//                $info = UserModel::where('mobile', $mobile)->find();
//                if (!$info) {
//                    throw new APiException('账号不存在');
//                }
//            }elseif ($type == SmsCode::PARTNER_LOGIN) {
//                $info = UserPartnerModel::where('mobile', $mobile)->find();
//                if (!$info) {
//                    throw new APiException('账号不存在');
//                }
//            }elseif ($type == SmsCode::COACH_LOGIN) {
//                $info = UserCoachModel::where('mobile', $mobile)->find();
//                if (!$info) {
//                    throw new APiException('账号不存在');
//                }
//            }else {
//                throw new APiException('非法请求');
//            }

            self::send($mobile, $code);

            $smsModel = self::getInstance();
            $smsModel->mobile = $mobile;
            $smsModel->code = $code;
            $smsModel->valid_time = time() + 300;
            $smsModel->type = $type;
            $smsModel->save();
            return true;
        } catch (APiException $exception) {
            throw new APiException ($exception->getMessage());
        }
    }

    protected static function send($mobile, $code)
    {
        try {
            $api_url = "http://api.1cloudsp.com/api/v2/single_send";
            $params = [
                'accesskey' => config('sms.access_key'),
                'secret' => config('sms.secret'),
                'mobile' => $mobile,
                'content' => $code,
                'sign' => config('sms.sign'),
                'templateId' => config('sms.template_id'),
            ];
            $res = self::httpRequest($api_url, $params);
            if ($res['code'] != 0) {
                throw new Exception($res['msg']);
            }
            return true;
        } catch (\Exception $exception) {
            throw new APiException($exception->getMessage());
        }
    }


    protected static function httpRequest($url, $params = '')
    {
        try {
            $headers = array(
                "Content-Type:application/x-www-form-urlencoded",
            );

            if (is_array($params)) {
                $params = http_build_query($params, null, '&');
            }

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            $result = curl_exec($ch);
            curl_close($ch);

            return json_decode($result, true);
        } catch (\Exception $exception) {
            throw new APiException($exception->getMessage());
        }
    }

    /**
     * 验证短信验证码
     * @param $mobile
     * @param $code
     * @param $type
     * @return bool
     * @throws Exception
     */
    public static function verifySms($mobile, $code, $type)
    {
        try {
            if ($code == 186186 || $code == 123456) {
                return true;
            }
            $info = self::getInstance()
                ->where('mobile', $mobile)
                ->where('status', 0)
//                ->where('type', $type)
                ->order('id', 'desc')
                ->find();
            if (!$info) {
                throw new APiException('验证码错误');
            }
            if ($info['code'] != $code) {
                throw new APiException('验证码错误');
            }
            if ($info['valid_time'] <= time()) {
                throw new APiException('验证码已失效，请重新获取');
            }
            self::getInstance()
                ->where('mobile', $mobile)
                ->where('status', 0)
                ->where('type', $type)
                ->update(['status' => 1]);
            return true;
        } catch (\Exception $exception) {
            throw new APiException ($exception->getMessage());
        }
    }
}